#include "Gateway_Node.h"

#include "sle_low_latency.h"
#include "sle_connection_manager.h"
#include "sle_ssap_client.h"
#include "sle_client.h"
#include "sle_node_list.h"

#include "SerialScreen.h"
#include "bsp_led.h"
#include "bsp_key.h"
#include "bsp_beep.h"
#include "bsp_uart.h"

#include "cJSON.h"

#include "wifi_sta_connect.h"
#include "NetworkProcessing.h"
#include <string.h>
#include <stdio.h>
#define CODE_LOG "[ShipSystem GatewayNode]"

#ifdef CONFIG_ENABLE_COMMUNICATION_SERIAL_CONFIG
#include "bsp_uart.h"

// 通信串口配置参数
static uint8_t g_uart_gui_rx_buff[CONFIG_COMMUNICATION_SERIAL_RX_BUF_SIZE] = {0};
static uart_buffer_config_t g_uart_gui_buffer_config = {
    .rx_buffer = g_uart_gui_rx_buff,
    .rx_buffer_size = CONFIG_COMMUNICATION_SERIAL_RX_BUF_SIZE,
};
#endif

// 任务句柄
osal_task *g_TaskHandle_SystemGatewayBleInit = NULL;    // 系统BLE初始化配置任务
osal_task *g_TaskHandle_SystemGatewayWifiConfig = NULL; // 系统网关WiFi配置任务
osal_task *g_TaskHandle_LedBlinky = NULL;               // LED闪烁任务
osal_task *g_TaskHandle_SystemDataUpdate = NULL;        // 系统数据更新任务
osal_task *g_TaskHandle_SystemEventHandle = NULL;       // 系统事件处理任务

// 任务函数声明
static void *ShipSystem_SystemGatewayWifiConfig_task(const char *arg);
static void *ShipSystem_LedBlinky_task(const char *arg);
static void *ShipSystem_SystemDataUpdate_task(const char *arg);
static void *ShipSystem_SystemEventHandle_task(const char *arg);
static void *ShipSystem_SystemGatewayInit_task(const char *arg);

// 事件句柄
osal_event g_EventHandle_SystemDataUpdate; // 系统数据更新事件
osal_event g_EventHandle_SystemEvent;      // 系统事件

// 系统数据
struct SystemData_t g_system_data = {
    .Temperature = 0, // 温度值， 单位：0.1摄氏度
    .Humidity = 0,    // 湿度值， 单位：0.1%
    .Light = 0,       // 光照强度
    .MotprSpeed = 70, // 电机速度， 取值范围：0-100
};
char environment_data[9][15];
char ship[3][10];
/**
 * @brief  解析SLE通信的Json消息数据。
 * @param  [in] msg_str Json消息数据字符串。
 * @param  [out] msg_data_type 消息数据类型。
 * @param  [in] msg_data_type_len 消息数据类型存储区大小。
 * @param  [out] msg_data_value 消息数据值。
 * @retval ERRCODE_SUCC 成功。
 * @retval Other        失败，参考 @ref errcode_t 。
 */
static errcode_t cJSON_SleMessageParse(char *msg_str, char *msg_data_type, uint16_t msg_data_type_len, uint16_t *msg_data_value)
{
    // 检查函数参数
    if (msg_str == NULL || msg_data_type == NULL || msg_data_type_len == 0 || msg_data_value == NULL)
    {
        osal_printk("%s cJSON_SleMessageParse invalid param\n", CODE_LOG);
        return ERRCODE_INVALID_PARAM;
    }

    // 解析cJSON消息
    cJSON *msg_cjson = cJSON_Parse(msg_str);
    if (msg_cjson == NULL)
    {
        const char *error_str = cJSON_GetErrorPtr();
        if (error_str != NULL)
        {
            osal_printk("%s cJSON_Parse failed:: %s\n", CODE_LOG, error_str);
        }
        else
        {
            osal_printk("%s cJSON_Parse failed\n", CODE_LOG);
        }

        return ERRCODE_INVALID_PARAM;
    }

    // 解析cJSON消息
    cJSON *cjson_msg_data_type = cJSON_GetObjectItemCaseSensitive(msg_cjson, "temperature");
    cJSON *cjson_msg_data_value = cJSON_GetObjectItemCaseSensitive(msg_cjson, "value");

    // 数据检查
    if (!cJSON_IsString(cjson_msg_data_type) || !cJSON_IsNumber(cjson_msg_data_value) || (cjson_msg_data_type->valuestring == NULL))
    {
        osal_printk("%s cJSON_SleMessageParse invalid data\n", CODE_LOG);

        cJSON_Delete(msg_cjson);
        return ERRCODE_FAIL;
    }
    if (cjson_msg_data_type->valuestring[0] == '\0') // 检查数据类型是否为空
    {
        osal_printk("%s cjson_msg_data_type->valuestring is NULL\n", CODE_LOG);
        cJSON_Delete(msg_cjson);
        return ERRCODE_FAIL;
    }
    if (strlen(cjson_msg_data_type->valuestring) > msg_data_type_len) // 检查数据类型长度
    {
        osal_printk("%s msg_data_type is too small\n", CODE_LOG);

        cJSON_Delete(msg_cjson);
        return ERRCODE_FAIL;
    }

    // 数据拷贝
    strcpy((char *)msg_data_type, cjson_msg_data_type->valuestring);
    *msg_data_value = cjson_msg_data_value->valueint;

    // 释放内存
    cJSON_Delete(msg_cjson);

    return ERRCODE_SUCC;
}
errcode_t cJSON_environment_Parse(char *msg_str, uint8_t *mqtt_data, uint8_t *mqtt_data2)
{
    // 解析cJSON消息
    cJSON *msg_cjson = cJSON_Parse(msg_str);
    if (msg_cjson == NULL)
    {
        const char *error_str = cJSON_GetErrorPtr();
        if (error_str != NULL)
        {
            osal_printk("%s cJSON_Parse failed:: %s\n", CODE_LOG, error_str);
        }
        else
        {
            osal_printk("%s cJSON_Parse failed\n", CODE_LOG);
        }

        return ERRCODE_INVALID_PARAM;
    }
    cJSON_AddStringToObject(msg_cjson, "name", "device1");
    char *string = cJSON_Print(msg_cjson);

    uint8_t intdext = 0;
    if (!strcmp(cJSON_GetObjectItemCaseSensitive(msg_cjson, "equipment")->valuestring, "collect"))
    {
        intdext = 1;
        strcpy(environment_data[0], cJSON_GetObjectItemCaseSensitive(msg_cjson, "temperature")->valuestring); // 温度
        strcpy(environment_data[1], cJSON_GetObjectItemCaseSensitive(msg_cjson, "hum")->valuestring);         // 湿度
        strcpy(environment_data[2], cJSON_GetObjectItemCaseSensitive(msg_cjson, "illuminance")->valuestring); // 光照度
        strcpy(environment_data[3], cJSON_GetObjectItemCaseSensitive(msg_cjson, "water_temp")->valuestring);  // 水温
        strcpy(environment_data[4], cJSON_GetObjectItemCaseSensitive(msg_cjson, "PH")->valuestring);          // PH
        strcpy(environment_data[5], cJSON_GetObjectItemCaseSensitive(msg_cjson, "solubility")->valuestring);  // 溶解度
        strcpy(environment_data[6], cJSON_GetObjectItemCaseSensitive(msg_cjson, "turbidity")->valuestring);   // 浑浊度
        strcpy(environment_data[7], cJSON_GetObjectItemCaseSensitive(msg_cjson, "longitude")->valuestring);   // 经度
        strcpy(environment_data[8], cJSON_GetObjectItemCaseSensitive(msg_cjson, "latitude")->valuestring);    // 纬度

        memmove(mqtt_data, string, strlen(string) + 1);
    }
    else if (!strcmp(cJSON_GetObjectItemCaseSensitive(msg_cjson, "equipment")->valuestring, "control"))
    {
        intdext = 2;
        strcpy(ship[0], cJSON_GetObjectItemCaseSensitive(msg_cjson, "speed")->valuestring);       // 速度
        strcpy(ship[1], cJSON_GetObjectItemCaseSensitive(msg_cjson, "angle")->valuestring);       // 角度
        strcpy(ship[2], cJSON_GetObjectItemCaseSensitive(msg_cjson, "electricity")->valuestring); // 电量

        memmove(mqtt_data2, string, strlen(string) + 1);
    }

    cJSON_Delete(msg_cjson);
    return intdext;
}
/**
 * @brief  创建电机控制Json消息数据。
 * @param  [in] mode 电机控制模式。
 * @param  [in] speed 电机速度。 范围0-100, 0为停止, 100为最大速度
 * @retval 成功， 返回Json消息数据字符串。该字符串使用完成需要使用 free() 释放内存。
 * @retval 失败， 返回 NULL。
 */
char *cJSON_SleMotorControlMessageCreat(char *mode, uint16_t speed)
{
    // 检查函数参数
    if (mode == NULL || speed > 100)
    {
        osal_printk("%s cJSON_SleMotorControlMessageCreat invalid param\n", CODE_LOG);
        return NULL;
    }

    // 创建JSON对象
    cJSON *root = cJSON_CreateObject();
    if (root == NULL)
    {
        osal_printk("%s cJSON_CreateObject fail\r\n", CODE_LOG);

        return NULL;
    }

    // 添加电机控制消息标识
    if (cJSON_AddStringToObject(root, "type", "motor_control") == NULL)
    {
        osal_printk("%s cJSON_AddStringToObject type fail\r\n", CODE_LOG);

        cJSON_Delete(root);
        return NULL;
    }

    // 添加电机控制模式
    if (cJSON_AddStringToObject(root, "mode", mode) == NULL)
    {
        osal_printk("%s cJSON_AddStringToObject mode fail\r\n", CODE_LOG);

        cJSON_Delete(root);
        return NULL;
    }

    // 添加电机控制速度
    if (cJSON_AddNumberToObject(root, "speed", speed) == NULL)
    {
        osal_printk("%s cJSON_AddNumberToObject speed fail\r\n", CODE_LOG);

        cJSON_Delete(root);
        return NULL;
    }

    // 将JSON对象转换为字符串
    char *json_string = cJSON_Print(root);

    // 释放JSON对象，并返回字符串
    cJSON_Delete(root);
    return json_string;
}
uint8_t mqtt_sampling_data[350];
uint8_t mqtt_control_data[200];
uint8_t rx_intdex;
// SLE通知消息回调函数
void sle_notification_cb(uint8_t client_id, uint16_t conn_id, ssapc_handle_value_t *data, errcode_t status)
{
    unused(client_id);
    unused(conn_id);
    unused(status);
    // osal_printk("%s(sle_notification_cb) sle uart recived data[%d] : %s\n", CODE_LOG, data->data_len, (char *)data->data);

#ifdef CONFIG_ENABLE_COMMUNICATION_SERIAL_CONFIG
    // 数据转发到通信串口中
    bsp_uart_send_data(CONFIG_COMMUNICATION_SERIAL_UART_ID, data->data, data->data_len); // 发送数据
#endif

    // 解析JSON数据
    char msg_data_type[32] = {0};
    uint16_t msg_data_value = 0;

    // osal_printk("%s", data->data); // 打印接收信息
    rx_intdex = cJSON_environment_Parse((char *)data->data, mqtt_sampling_data, mqtt_control_data);
    if (rx_intdex)
    {
        // 根据数据类型处理数据
        osal_event_write(&g_EventHandle_SystemDataUpdate, SYSTEM_DATA_UPDATE_EVENT_TEMPERATURE); // 发送温度更新事件
    }
}

// SLE指示消息回调函数
void sle_indication_cb(uint8_t client_id, uint16_t conn_id, ssapc_handle_value_t *data, errcode_t status)
{
    unused(client_id);
    unused(conn_id);
    unused(status);
    osal_printk("%s(sle_indication_cb) sle uart recived data : %s\r\n", CODE_LOG, data->data);
}

/***** 系统任务处理处理 *****/
// 系统LED闪烁任务
static void *ShipSystem_LedBlinky_task(const char *arg)
{
    unused(arg);

    while (1)
    {
        bsp_led_toggle(LED1);
        osal_msleep(500);
    }

    return NULL;
}

// 数据更新任务
static void *ShipSystem_SystemDataUpdate_task(const char *arg)
{
    unused(arg);

    // 创建系统数据更新事件
    if (osal_event_init(&g_EventHandle_SystemDataUpdate) != OSAL_SUCCESS)
    {
        osal_printk("ERROR:%s Init g_EventHandle_SystemDataUpdate failed\n", CODE_LOG);
        return NULL;
    }

    // 等待系统数据更新事件
    while (1)
    {
        char oled_data[8] = {0};

        uint32_t event = osal_event_read(&g_EventHandle_SystemDataUpdate, SYSTEM_DATA_UPDATE_EVENT_ALL, OSAL_WAIT_FOREVER, OSAL_WAITMODE_OR);
        if (event & SYSTEM_DATA_UPDATE_EVENT_TEMPERATURE) // 数据更新
        {

            if (rx_intdex == 1) // 更新屏幕数据显示
            {
                data_report(environment_data, 9);
            }
            else if (rx_intdex == 2)
            {
                data_report2(ship, 3);
            }
        }
        // 清除系统数据更新事件
        osal_event_clear(&g_EventHandle_SystemDataUpdate, event);
    }

    // 销毁系统数据更新事件
    osal_event_destroy(&g_EventHandle_SystemDataUpdate);

    return NULL;
}

// 系统事件处理任务
static void *ShipSystem_SystemEventHandle_task(const char *arg)
{
    unused(arg);

    // 创建系统事件
    if (osal_event_init(&g_EventHandle_SystemEvent) != OSAL_SUCCESS)
    {
        osal_printk("ERROR:%s Init g_EventHandle_SystemEvent failed\n", CODE_LOG);
        return NULL;
    }

    // 等待系统事件
    while (1)
    {
        uint32_t event = osal_event_read(&g_EventHandle_SystemEvent, SYSTEM_EVENT_ALL, OSAL_WAIT_FOREVER, OSAL_WAITMODE_OR);
        if (event & SYSTEM_EVENT_KEY1_REESS) // 按键1按下事件
        {
            osal_printk("%s Key1 pressed\n", CODE_LOG);

            // 写入打开风扇事件
            // osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_FAN_ON);
        }
        if (event & SYSTEM_EVENT_KEY1_RELEASE) // 按键1释放事件
        {
            osal_printk("%s Key1 released\n", CODE_LOG);

            // 处理按键1释放事件
        }
        if (event & SYSTEM_EVENT_KEY2_REESS) // 按键2按下事件
        {
            osal_printk("%s Key2 pressed\n", CODE_LOG);

            // 写入关闭风扇事件
            // osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_FAN_OFF);
        }
        if (event & SYSTEM_EVENT_KEY2_RELEASE) // 按键2释放事件
        {
            osal_printk("%s Key2 released\n", CODE_LOG);

            // 处理按键2释放事件
        }
        if (event & SYSTEM_EVENT_MOTOR_STOP) // 电机停止事件
        {
            osal_printk("%s System_event handle motor_stop\n", CODE_LOG);

            // 查询电机控制设备节点信息
            sle_node_list_t *sle_node = SLE_NodeList_Find("MOTOR", strlen("MOTOR"));
            if (sle_node != NULL)
            {
                osal_printk("%s sle_node->device_info.sle_conn_id: %d\n", CODE_LOG, sle_node->device_info.sle_conn_id);

                char *ShowBuf = cJSON_SleMotorControlMessageCreat("stop", 0);
                if (ShowBuf != NULL)
                {
                    // osal_printk("%s %s\n", CODE_LOG, ShowBuf);
                    ssapc_write_param_t *sle_send_param = get_g_sle_send_param();
                    sle_send_param->data_len = strlen(ShowBuf) + 1;
                    sle_send_param->data = (uint8_t *)ShowBuf;
                    ssapc_write_req(0, sle_node->device_info.sle_conn_id, sle_send_param);

                    free(ShowBuf);
                }
            }
        }
        if (event & SYSTEM_EVENT_MOTOR_ADVANCE) // 电机前进事件
        {
            osal_printk("%s System_event handle motor_advance\n", CODE_LOG);

            // 查询电机控制设备节点信息
            sle_node_list_t *sle_node = SLE_NodeList_Find("MOTOR", strlen("MOTOR"));
            if (sle_node != NULL)
            {
                osal_printk("%s sle_node->device_info.sle_conn_id: %d\n", CODE_LOG, sle_node->device_info.sle_conn_id);

                char *ShowBuf = cJSON_SleMotorControlMessageCreat("advance", g_system_data.MotprSpeed);
                if (ShowBuf != NULL)
                {
                    // osal_printk("%s %s\n", CODE_LOG, ShowBuf);
                    ssapc_write_param_t *sle_send_param = get_g_sle_send_param();
                    sle_send_param->data_len = strlen(ShowBuf) + 1;
                    sle_send_param->data = (uint8_t *)ShowBuf;
                    ssapc_write_req(0, sle_node->device_info.sle_conn_id, sle_send_param);

                    free(ShowBuf);
                }
            }
        }
        if (event & SYSTEM_EVENT_MOTOR_BACK) // 电机后退事件
        {
            osal_printk("%s System_event handle motor_back\n", CODE_LOG);

            // 查询电机控制设备节点信息
            sle_node_list_t *sle_node = SLE_NodeList_Find("MOTOR", strlen("MOTOR"));
            if (sle_node != NULL)
            {
                osal_printk("%s sle_node->device_info.sle_conn_id: %d\n", CODE_LOG, sle_node->device_info.sle_conn_id);

                char *ShowBuf = cJSON_SleMotorControlMessageCreat("back", g_system_data.MotprSpeed);
                if (ShowBuf != NULL)
                {
                    // osal_printk("%s %s\n", CODE_LOG, ShowBuf);
                    ssapc_write_param_t *sle_send_param = get_g_sle_send_param();
                    sle_send_param->data_len = strlen(ShowBuf) + 1;
                    sle_send_param->data = (uint8_t *)ShowBuf;
                    ssapc_write_req(0, sle_node->device_info.sle_conn_id, sle_send_param);

                    free(ShowBuf);
                }
            }
        }
        if (event & SYSTEM_EVENT_MOTOR_LEFT) // 电机左转事件
        {
            osal_printk("%s System_event handle motor_left\n", CODE_LOG);

            // 查询电机控制设备节点信息
            sle_node_list_t *sle_node = SLE_NodeList_Find("MOTOR", strlen("MOTOR"));
            if (sle_node != NULL)
            {
                osal_printk("%s sle_node->device_info.sle_conn_id: %d\n", CODE_LOG, sle_node->device_info.sle_conn_id);

                char *ShowBuf = cJSON_SleMotorControlMessageCreat("left", g_system_data.MotprSpeed);
                if (ShowBuf != NULL)
                {
                    // osal_printk("%s %s\n", CODE_LOG, ShowBuf);
                    ssapc_write_param_t *sle_send_param = get_g_sle_send_param();
                    sle_send_param->data_len = strlen(ShowBuf) + 1;
                    sle_send_param->data = (uint8_t *)ShowBuf;
                    ssapc_write_req(0, sle_node->device_info.sle_conn_id, sle_send_param);

                    free(ShowBuf);
                }
            }
        }
        if (event & SYSTEM_EVENT_MOTOR_RIGHT) // 电机右转事件
        {
            osal_printk("%s System_event handle motor_right\n", CODE_LOG);

            // 查询电机控制设备节点信息
            sle_node_list_t *sle_node = SLE_NodeList_Find("MOTOR", strlen("MOTOR"));
            if (sle_node != NULL)
            {
                osal_printk("%s sle_node->device_info.sle_conn_id: %d\n", CODE_LOG, sle_node->device_info.sle_conn_id);

                char *ShowBuf = cJSON_SleMotorControlMessageCreat("right", g_system_data.MotprSpeed);
                if (ShowBuf != NULL)
                {
                    // osal_printk("%s %s\n", CODE_LOG, ShowBuf);
                    ssapc_write_param_t *sle_send_param = get_g_sle_send_param();
                    sle_send_param->data_len = strlen(ShowBuf) + 1;
                    sle_send_param->data = (uint8_t *)ShowBuf;
                    ssapc_write_req(0, sle_node->device_info.sle_conn_id, sle_send_param);

                    free(ShowBuf);
                }
            }
        }

        // 清除系统数据更新事件
        osal_event_clear(&g_EventHandle_SystemEvent, event);
    }

    // 销毁系统数据更新事件
    osal_event_destroy(&g_EventHandle_SystemEvent);

    return NULL;
}

// 按键1按下处理函数
void ShipSystem_Key1_PressHandle(void)
{
    // osal_printk("%s Key1 pressed\n", CODE_LOG);

    // 触发按键1按下事件
    osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_KEY1_REESS);
}

// 按键2按下处理函数
void ShipSystem_Key2_PressHandle(void)
{
    // osal_printk("%s Key2 pressed\n", CODE_LOG);

    // 触发按键2按下事件
    osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_KEY2_REESS);
}

/***** 系统串口通信处理 *****/
#ifdef CONFIG_ENABLE_COMMUNICATION_SERIAL_CONFIG
// 通信串口接收回调函数
static void communication_uart_rx_callback(const void *buffer, uint16_t length, bool error)
{
    if (buffer == NULL || length == 0)
    {
        return;
    }

    // 打印接收的数据
    osal_printk("%s uart_rx[%d]: %s \n", CODE_LOG, length, (char *)buffer);

    // 解析JSON数据
    char msg_data_type[32] = {0};
    uint16_t msg_data_value = 0;
    // if (cJSON_SleMessageParse((char *)buffer, msg_data_type, 32, &msg_data_value) == ERRCODE_SUCC)
    // {
    //     // osal_printk("%s msg_data_type: %s\n", CODE_LOG, msg_data_type);
    //     // 根据数据类型处理数据
    //     if (strcmp(msg_data_type, "fan") == 0) // 风扇控制
    //     {
    //         if (msg_data_value == 1) // 开风扇
    //         {
    //             osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_FAN_ON);
    //         }
    //         else if (msg_data_value == 0) // 关风扇
    //         {
    //             osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_FAN_OFF);
    //         }
    //     }
    //     else if (strcmp(msg_data_type, "alarm") == 0) // 报警器控制
    //     {
    //         if (msg_data_value == 1) // 开报警器
    //         {
    //             osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_ALARM_ON);
    //         }
    //         else if (msg_data_value == 0) // 关报警器
    //         {
    //             osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_ALARM_OFF);
    //         }
    //     }
    // }
}
#endif

// 系统网关设备初始化任务
static void *ShipSystem_SystemGatewayInit_task(const char *arg)
{
    unused(arg);

    osal_printk("%s System startup...\n", CODE_LOG);

    // 初始化串口屏
    SerialScreen_Init();

    // 初始化按键
    bsp_key_init(KEY1, CONFIG_KEY1_PIN);
    bsp_key_init(KEY2, CONFIG_KEY2_PIN);

    // 初始化LED
    bsp_led_init(LED1, CONFIG_LED1_PIN);
    bsp_led_init(LED2, CONFIG_LED2_PIN);

    // 初始化蜂鸣器
    bsp_beep_init(CONFIG_BEEP_PIN);

#ifdef CONFIG_ENABLE_COMMUNICATION_SERIAL_CONFIG
    // 初始化通信串口
    if (bsp_uart_init(CONFIG_COMMUNICATION_SERIAL_UART_ID, CONFIG_COMMUNICATION_SERIAL_BAUDRATE, &g_uart_gui_buffer_config) != ERRCODE_SUCC)
    {
        osal_printk("ERROR:%s SerialScreen_Init uart init fail!\n", CODE_LOG);
    }
    if (bsp_uart_register_rx(CONFIG_COMMUNICATION_SERIAL_UART_ID, communication_uart_rx_callback) != ERRCODE_SUCC) // 注册串口接收回调函数
    {
        osal_printk("ERROR:%s SerialScreen_Init uart register rx fail!\n", CODE_LOG);
    }
#endif

#ifdef CONFIG_ENABLE_WIFI_IOT_CONFIG
    // 获取设备网络连接参数，并初始化WiFi
    if (SystemGateway_WifiConfig() != ERRCODE_SUCC)
    {
        // 网络相关参数置0
        g_wifi_mode = 0;
        g_wifi_network_mode = 0;
        g_iot_type = 0;
    }
#endif

    // 初始化SLE_Client
    sle_client_init(sle_notification_cb, sle_indication_cb);

    // 创建系统数据更新任务
    osal_msleep(50);
    osal_kthread_lock();
    g_TaskHandle_SystemDataUpdate = osal_kthread_create((osal_kthread_handler)ShipSystem_SystemDataUpdate_task, 0, "SystemDataUpdate_Task", 0x1000);
    if (g_TaskHandle_SystemDataUpdate != NULL)
    {
        osal_kthread_set_priority(g_TaskHandle_SystemDataUpdate, SYSTEM_TASK_PRIORITY_HIGH);
    }
    else
    {
        osal_printk("ERROR:%s Create SystemDataUpdate_Task failed!\n", CODE_LOG);
    }
    osal_kthread_unlock();

    // 创建系统事件处理任务
    osal_msleep(50);
    osal_kthread_lock();
    g_TaskHandle_SystemEventHandle = osal_kthread_create((osal_kthread_handler)ShipSystem_SystemEventHandle_task, 0, "SystemEventHandle_Task", 0x1000);
    if (g_TaskHandle_SystemEventHandle != NULL)
    {
        osal_kthread_set_priority(g_TaskHandle_SystemEventHandle, SYSTEM_TASK_PRIORITY_HIGH);
    }
    else
    {
        osal_printk("ERROR:%s Create SystemEventHandle_Task failed!\n", CODE_LOG);
    }
    osal_kthread_unlock();

    // 按键设备回调函数注册
    bsp_key_enable_interrupt(KEY1, ShipSystem_Key1_PressHandle, NULL);
    bsp_key_enable_interrupt(KEY2, ShipSystem_Key2_PressHandle, NULL);

    // 创建系统LED指示灯任务
    osal_msleep(50);
    osal_kthread_lock();
    g_TaskHandle_LedBlinky = osal_kthread_create((osal_kthread_handler)ShipSystem_LedBlinky_task, 0, "LedBlinky_Task", 0x200);
    if (g_TaskHandle_LedBlinky != NULL)
    {
        osal_kthread_set_priority(g_TaskHandle_LedBlinky, SYSTEM_TASK_PRIORITY_LOW);
    }
    else
    {
        osal_printk("ERROR:%s Create LedBlinky_Task failed!\n", CODE_LOG);
    }
    osal_kthread_unlock();

    return NULL;
}

static uint8_t rx_buff[512] = {0};
bool rx_4G;
bool network;
static uart_buffer_config_t buffer_config_4G = {
    .rx_buffer = rx_buff,
    .rx_buffer_size = 512,
};
uint8_t MQTT_state;
void uart_rx_callback_4G(const void *buffer, uint16_t length, bool error)
{
    const char *buff = buffer;
    osal_printk("S:%s\n", buff);
    if (!network && strstr(buff, "OK"))
        rx_4G = 1;
    if (!network && strstr(buff, "0,0,0"))
    {
        network_state(1);
        network = 1;
    }
    if (network && strstr(buff, ",3"))
    {
        MQTT_state = 1;
    }
}

char AT_4G_init[][50] = {"AT+CGDCONT=1,\"IP\",\"ctnet\"\n\r",
                         "AT+CGATT=1\r\n",

                         "AT+QMTOPEN=0,\"122.51.61.17\",1883 \r\n",
                         "AT+QMTCONN=0,\"ship_data\" \r\n"};
osal_task *MQTT_task_handle = NULL;
static void *MQTT_4G_task(const char *arg)
{
    bsp_uart_init(UART_BUS_1, 115200, &buffer_config_4G);
    bsp_uart_register_rx(UART_BUS_1, uart_rx_callback_4G);
    //  创建系统事件
    for (uint8_t i = 0; i < 4;)
    {
        bsp_uart_send_data(UART_BUS_1, (uint8_t *)AT_4G_init[i], strlen(AT_4G_init[i]));
        osal_printk("F:%s,%d\n", AT_4G_init[i], strlen(AT_4G_init[1]));
        osal_msleep(1000);
        if (rx_4G)
        {
            i++;
            rx_4G = 0;
        }
    }
    bsp_uart_send_data(UART_BUS_1, (uint8_t *)"AT+CREG?\r\n", strlen("AT+CREG?\r\n")); // 每十秒检查网络状态

    while (1)
    {
        if (mqtt_sampling_data[0] != '\0' || mqtt_control_data[0] != '\0')
        {
            uint8_t mqtt_at[50];
            bsp_uart_send_data(UART_BUS_1, (uint8_t *)"AT+QMTCONN?\r\n", strlen("AT+QMTCONN?\r\n"));
            osal_msleep(500);
            if (MQTT_state)
            {
                osal_printk("FB:%s\n", mqtt_at);
                if (mqtt_sampling_data[0] != '\0')
                {
                    sprintf_s((char *)mqtt_at, 50, "AT+QMTPUBEX=0,0,0,0,\"test/sampling_node\",%d\r\n", strlen((char *)mqtt_sampling_data));

                    bsp_uart_send_data(UART_BUS_1, mqtt_at, strlen((char *)mqtt_at));
                    osal_msleep(200);
                    bsp_uart_send_data(UART_BUS_1, mqtt_sampling_data, strlen((char *)mqtt_sampling_data));
                    mqtt_sampling_data[0] = '\0';

                    osal_msleep(500);
                }

                if (mqtt_control_data[0] != '\0')
                {
                    sprintf_s((char *)mqtt_at, 50, "AT+QMTPUBEX=0,0,0,0,\"test/control_node\",%d\r\n", strlen((char *)mqtt_control_data));

                    bsp_uart_send_data(UART_BUS_1, mqtt_at, strlen((char *)mqtt_at));
                    osal_msleep(200);
                    bsp_uart_send_data(UART_BUS_1, mqtt_control_data, strlen((char *)mqtt_control_data));
                    mqtt_control_data[0] = '\0';
                }
            }

            MQTT_state = 0;
        }

        osal_msleep(2000);
    }
    osal_kthread_suspend(MQTT_task_handle);

    // 销毁系统数据更新事件
    return NULL;
}

static void ShipSystem_SystemGateway(void)
{
    // 创建系统初始化任务
    osal_task *task_handle = NULL;
    osal_kthread_lock();
    task_handle = osal_kthread_create((osal_kthread_handler)ShipSystem_SystemGatewayInit_task, 0, "ShipSystem_SystemGatewayInit_Task", 0x1000);
    if (task_handle != NULL)
    {
        osal_kthread_set_priority(task_handle, SYSTEM_TASK_PRIORITY_NORMAL);
    }
    MQTT_task_handle = osal_kthread_create((osal_kthread_handler)MQTT_4G_task, 0, "MQTT_4G_task", 0x1000);
    if (MQTT_task_handle != NULL)
    {
        osal_kthread_set_priority(MQTT_task_handle, SYSTEM_TASK_PRIORITY_NORMAL);
    }

    osal_kthread_unlock();
}

/* Run the ShipSystem_SystemGateway. */
app_run(ShipSystem_SystemGateway);